import { useState, useEffect, useContext } from 'react';
import { NavBar, Button, Dialog, List, Input, Image, Switch } from "antd-mobile";
import { AddCircleOutline } from 'antd-mobile-icons';
import { useHistory, useRouteMatch } from "react-router-dom";

import GroupMemberSelectContactor from '../../../components/GroupMembersSelectContactor';
import AvatarImage from '../../../components/AvatarImage';

import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const { params: { cid } } = useRouteMatch();
  const [list, setList] = useState([]);
  const [admin, setAdmin] = useState([]);
  const [groupMemberSelectContactorProp, setGroupMemberSelectContactorProp] = useState({visible: false, getListApi: '', onOk: () => {}, onClose: () => {}});

  // 获取群主、群管理员信息
  const getAdminUserInfo = async () => {
    const { adminUsers, ownerId } = await mySdkStore.sdk.querySingleConversation({ cid });
    setAdmin([...adminUsers, ownerId]);
    if (adminUsers.length) {
      const { rows } = await mySdkStore.sdk.batchQueryUserInfo({ userIds: adminUsers });
      setList(rows);
    }
  }

  // 移除群管理员事件
  const handleRemove = async (userId) => {
    await mySdkStore.sdk.updateGroup({ cid, updateType: 'remove_admin_user', group: { adminUsers: [userId]} });
    setList((list) => list.filter(item => item.userId !== userId));
  };

  // 新增群管理员
  const handleAdd = async (userIds) => {
    const adminUsers = userIds.map(({ userId }) => userId);
    await mySdkStore.sdk.updateGroup({ cid, updateType: 'add_admin_user', group: { adminUsers } });
    setGroupMemberSelectContactorProp({ visible: false});
    getAdminUserInfo();
  }

  // 点击“添加群管理员”按钮，展示“选择群管理员”界面
  const handleAddAdminVisible = async () => {
    setGroupMemberSelectContactorProp({
      visible: true,
      title: '添加群管理员',
      cid,
      getListApi: 'listGroupMembers',
      listFilterFunc: (list) => list.filter(item => admin.indexOf(item.userId) === -1),
      onOk: handleAdd,
      onClose: () => setGroupMemberSelectContactorProp({ visible: false})
    });
  }

  useEffect(() => {
    getAdminUserInfo();
  }, []);

  return (<div className="groupAdminPage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>群管理员</NavBar>
      <List style={{ marginTop: 12, '--border-inner': 0 }}>
        {list.map(item => {
          return <List.Item
            key={item.userId}
            extra={<Button style={{ '--background-color': 'rgba(0,34,60,.2)', '--text-color': 'rgba(0,0,0,0.65)' }} size="small" onClick={() => handleRemove(item.userId)}>移除</Button>}
            prefix={<AvatarImage
            src={item.avatarUrl}
            nickName={item.nickName}
            userName={item.userName}
            userId={item.userId}
            style={{ borderRadius: 8 }}
            fit='cover'
            width={40}
            height={40}
          />}>{item.userName}</List.Item>
        })}
      </List>
      <div className="btnBar">
        <a onClick={handleAddAdminVisible}>
          <AddCircleOutline style={{ marginRight: 14 }} />
          添加群管理员
        </a>
      </div>
      { groupMemberSelectContactorProp.visible && <GroupMemberSelectContactor {...groupMemberSelectContactorProp} /> }
    </div>
  )
}